package com.changgou.common.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //顺带把其它头部的信息也携带过去
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if (requestAttributes!=null){
            //获取request
            HttpServletRequest request = requestAttributes.getRequest();

            //获取请求头部的名称
            Enumeration<String> headerNames = request.getHeaderNames();

            while (headerNames.hasMoreElements()){
                //请求头名称
                String name = headerNames.nextElement();

                //请求头对应的值
                String value = request.getHeader(name);

                //设置请求头，传递到微服务
                requestTemplate.header(name,value);
            }
        }
    }
}
